/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年9月10日 上午11:17:34
 */
package com.absir.appserv.system.asset;

import java.io.IOException;

import com.absir.appserv.system.bean.JPayTrade;
import com.absir.appserv.system.bean.value.JePayStatus;
import com.absir.appserv.system.helper.HelperEncrypt;
import com.absir.appserv.system.helper.HelperJson;
import com.absir.appserv.system.service.AnySdkService;
import com.absir.appserv.system.service.BeanService;
import com.absir.appserv.system.service.utils.PayUtils;
import com.absir.core.kernel.KernelDyna;
import com.absir.server.in.Input;
import com.absir.server.value.Body;
import com.absir.server.value.Param;
import com.absir.server.value.Server;

/**
 * @author absir
 *
 */
@Server
public class Asset_anysdk extends AssetServer {

	/**
	 * @param channel
	 * @param uapi_key
	 * @param uapi_secret
	 * @return
	 * @throws IOException
	 */
	@Body
	public void login(Input input) throws IOException {
		AnySdkService.ME.login(input);
	}

	/**
	 * @param enhanced_sign
	 * @param pay_status
	 * @param amount
	 * @param channel_number
	 * @param private_data
	 * @param input
	 * @return
	 */
	@Body
	public String notify(@Param String enhanced_sign, @Param String pay_status, @Param String amount, @Param String channel_number,
			@Param String private_data, Input input) {
		String signString = HelperJson.builderSignSortValues(HelperJson.buildParams(input.getParamMap()),
				new String[] { "sign", "enhanced_sign" }).toString();
		signString = HelperEncrypt.encryptionMD5(signString).toLowerCase()
				+ AnySdkService.ANY_SDK_CONFIGURE.getEnhancedMerchantKey();
		signString = HelperEncrypt.encryptionMD5(signString).toLowerCase();
		if (enhanced_sign.equals(signString)) {
			JPayTrade payTrade = BeanService.ME.get(JPayTrade.class, private_data);
			if (payTrade != null) {
				payTrade.setPlatform(AnySdkService.PLAT_FORM_NAME + "@" + channel_number);
				payTrade.setStatus(pay_status.equals("1") && KernelDyna.toFloat(amount) >= payTrade.getAmount() ? JePayStatus.PAYED
						: JePayStatus.ERROR);
				payTrade.setStatusData(pay_status);
				payTrade.setChannel(channel_number);
				if (payTrade.getStatus() == JePayStatus.PAYED) {
					PayUtils.proccessDone(payTrade);

				} else {
					BeanService.ME.merge(payTrade);
				}
			}

			return "ok";
		}

		return "fail";
	}

}
